<?php
/**
 * This function extracts the non-tags string and returns a correctly formatted string
 * It can handle all html entities e.g. &amp;, &quot;, etc..
 *
 * @param string $s
 * @param integer $srt
 * @param integer $len
 * @param bool/integer	Strict if this is defined, then the last word will be complete. If this is set to 2 then the last sentence will be completed.
 * @param string A string to suffix the value, only if it has been chopped.
 */
function html_substr( $s, $srt, $len = NULL, $strict=false, $suffix = NULL )
{
	if ( is_null($len) ){ $len = strlen( $s ); }
	
	$f = 'static $strlen=0; 
			if ( $strlen >= ' . $len . ' ) { return "><"; } 
			$html_str = html_entity_decode( $a[1] );
			$subsrt   = max(0, ('.$srt.'-$strlen));
			$sublen = ' . ( empty($strict)? '(' . $len . '-$strlen)' : 'max(@strpos( $html_str, "' . ($strict===2?'.':' ') . '", (' . $len . ' - $strlen + $subsrt - 1 )), ' . $len . ' - $strlen)' ) . ';
			$new_str = substr( $html_str, $subsrt,$sublen); 
			$strlen += $new_str_len = strlen( $new_str );
			$suffix = ' . (!empty( $suffix ) ? '($new_str_len===$sublen?"'.$suffix.'":"")' : '""' ) . ';
			return ">" . htmlentities($new_str, ENT_QUOTES, "UTF-8") . "$suffix<";';
	
	return preg_replace( array( "#<[^/][^>]+>(?R)*</[^>]+>#", "#(<(b|h)r\s?/?>){2,}$#is"), "", trim( rtrim( ltrim( preg_replace_callback( "#>([^<]+)<#", create_function(
            '$a',
          $f
        ), ">$s<"  ), ">"), "<" ) ) );
}

function substrhtml($str,$start,$len){

    $str_clean = substr(strip_tags($str),$start,$len);
    $pos = strrpos($str_clean, " ");
    if($pos === false) {
        $str_clean = substr(strip_tags($str),$start,$len);  
        }else
        $str_clean = substr(strip_tags($str),$start,$pos);

    if(preg_match_all('/\<[^>]+>/is',$str,$matches,PREG_OFFSET_CAPTURE)){

        for($i=0;$i<count($matches[0]);$i++){

            if($matches[0][$i][1] < $len){

                $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]);

            }else if(preg_match('/\<[^>]+>$/is',$matches[0][$i][0])){

                $str_clean = substr($str_clean,0,$matches[0][$i][1]) . $matches[0][$i][0] . substr($str_clean,$matches[0][$i][1]);

                break;

            }

        }

        return $str_clean;

    } else {
        $string = substr($str,$start,$len);
         $pos = strrpos($string, " ");
        if($pos === false) {
            return substr($str,$start,$len);
        }
            return substr($str,$start,$pos);

    }

}

function substr_rm_html($str, $start, $len) {
	return substr(strip_tags($str),$start,$len); 
	
}

?>